﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoFix.Base;
using BusinessLogicLayer.Manager;
using Common;
using Objects;
using System.Text;
using System.Web.UI.HtmlControls;
using System.IO;

namespace AutoFix
{
    public partial class edit_step : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// Holds the article in session
        /// </summary>
        private Article article = null;
        #endregion


        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return false; } }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Edit Step"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor }); }
        }

        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            article = this.PageSession.Article;
            if (!(Page.IsPostBack))
            {

                if (Request.QueryString["step"] != null)
                {
                    StepManager stepManager = new StepManager();
                    List<Step> steps = null;
                    try
                    {
                        steps = stepManager.GetSteps(Convert.ToInt32(Request.QueryString["step"]));
                        if (steps != null && steps.Count > 0)
                        {
                            if (steps[0].IsActive != false)
                            {
                                bool isVideo = steps[0].StepURL.Contains(".mp4");
                                if (isVideo)
                                {


                                    this.txtStepName.Text = steps[0].StepName;
                                    this.lblStepContentTitle.Visible = true;
                                    this.fleUploadVideo.Visible = true;
                                    itemHolder.Visible = true;
                                    StringBuilder pathToFile = new StringBuilder();
                                    pathToFile.Append(AppConfiguration.ArticlePath);
                                    pathToFile.Append("/");
                                    pathToFile.Append(this.PageSession.Article.ArticleID);
                                    pathToFile.Append("/");
                                    pathToFile.Append(steps[0].StepURL);
                                    string completePath = pathToFile.ToString();
                                    HtmlGenericControl videoSource = new HtmlGenericControl();
                                    videoSource.TagName = "source";
                                    videoSource.Attributes.Add("src", completePath);
                                    videoSource.Attributes.Add("type","video/mp4");
                                    this.vdoStep.Controls.Add(videoSource);
                                    pathToFile = null;

                                }
                                else
                                {
                                    this.txtContent.Visible = true;
                                    this.rqdStepContent.Visible = true;

                                    this.txtStepName.Text = steps[0].StepName;
                                    
                                    StringBuilder pathToFile = new StringBuilder();
                                    pathToFile.Append(AppConfiguration.ArticlePath);
                                    pathToFile.Append("/");
                                    pathToFile.Append(this.PageSession.Article.ArticleID);
                                    pathToFile.Append("/");
                                    pathToFile.Append(steps[0].StepURL);
                                    string completePath = Server.MapPath(pathToFile.ToString());
                                    this.txtContent.Text = LoadStepData(completePath);
                                    pathToFile = null;
                                }
                            }
                            else
                            {
                                this.pageActionMessage.InnerText = "The step might have been deleted. Cannot load step information";
                                this.pageActionMessage.Attributes.Add("class", "information-msg");
                            }
                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "Failed to load step information.";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                        }

                    }
                    catch (Exception)
                    {
                        this.pageActionMessage.InnerText = "Failed to load step information.";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                    finally
                    {
                        stepManager = null;
                        steps = null;
                    }
                }
            }
        }
        /// <summary>
        /// Handles the click event of the save step button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveStep_Click(object sender, EventArgs e)
        {
            StepManager stepManager = new StepManager();
            Step step = new Step();
            List<Step> steps = null;
            string fileName = string.Empty;
            string file = string.Empty;
            try
            {
                steps = stepManager.GetSteps(Convert.ToInt32(Request.QueryString["step"]));
                if (steps != null && steps.Count > 0)
                {
                    step.StepID = steps[0].StepID;
                    step.StepName = this.txtStepName.Text.Trim();
                    step.ArticleID = steps[0].ArticleID;
                    step.IsActive = true;

                    if ((int)ArticleEnums.Video == article.ArticleTypeID)
                    {
                        if (this.fleUploadVideo.HasFile)
                        {
                            if (this.fleUploadVideo.PostedFile.ContentType == "video/mp4")
                            {
                                Guid guid = Guid.NewGuid();
                                string pathToFile = AppConfiguration.ArticlePath + article.ArticleID + "/";
                                string fileToStore = guid + ".mp4";

                                string completeDirectoryPath = Server.MapPath(pathToFile);
                                if (!Directory.Exists(pathToFile))
                                {
                                    Directory.CreateDirectory(completeDirectoryPath);
                                    completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                                    if (!File.Exists(completeDirectoryPath))
                                    {
                                        file = completeDirectoryPath;
                                        step.StepURL = fileToStore;
                                        this.fleUploadVideo.SaveAs(file);
                                    }
                                }
                            }
                            else
                            {
                                this.pageActionMessage.InnerText = "Invalid video file. Only video/mp4 is allowed";
                                this.pageActionMessage.Attributes.Add("class", "error-msg");
                                return;
                            }
                        }
                        else
                        {
                            step.StepURL = steps[0].StepURL;
                        }
                    }

                    if ((int)ArticleEnums.Blog == article.ArticleTypeID)
                    {
                        string pathToFile = AppConfiguration.ArticlePath + article.ArticleID + "/" + steps[0].StepURL;
                        string lines = this.txtContent.Text;
                        string completePath = Server.MapPath(pathToFile);
                        System.IO.StreamWriter textFile = new System.IO.StreamWriter(completePath);
                        textFile.WriteLine(lines);
                        textFile.Close();

                        step.StepURL = steps[0].StepURL;
                    }
                    bool success = stepManager.UpdateStep(step);

                    if (success)
                    {
                        this.pageActionMessage.InnerText = "The step information was saved successfully.";
                        this.pageActionMessage.Attributes.Add("class", "success-msg");
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Failed to save the step.";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to save the step.";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                step = null;
                stepManager = null;
            }
        }
        #endregion

        #region [Private Methods]
        /// <summary>
        /// Reads the loaded  data
        /// </summary>
        /// <param name="stepURL">the step url</param>
        /// <returns>the lines in the text</returns>
        private string LoadStepData(string stepURL)
        {

            string lines = System.IO.File.ReadAllText(stepURL);
            return lines;

        }
        #endregion

    }
}